package com.microcm.system.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;

import com.microcm.common.CUtils;
import com.microcm.common.Final;
import com.microcm.common.SystemToolkit;
import com.microcmframework.core.BaseServlet;
import com.microcmframework.core.context.AppContext;

/**
 * 查询关键词TAG的商品
 * 
 * @author kansum
 */
public class SearchListGoodsServlet extends BaseServlet
{
	private static final long serialVersionUID = 1L;

	private int pageSize = 0;

	private int maxPageCount = 0;

	@Override
	public void init(ServletConfig cfg) throws ServletException
	{
		String _v = AppContext.getInstance().getSysPropValue("search.menu.goods.pagesize");
		this.pageSize = CUtils.isInteger(_v) ? Integer.parseInt(_v) : 0;
		_v = AppContext.getInstance().getSysPropValue("search.menu.goods.maxpage");
		this.maxPageCount = CUtils.isInteger(_v) ? Integer.parseInt(_v) : 0;
	}

	@Override
	protected void doProc(PrintWriter out, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		// 获得参数
		String keyword = URLDecoder.decode(req.getParameter("q"), "UTF-8");
		int page = CUtils.isInteger(req.getParameter("page")) ? Integer.parseInt(req.getParameter("page")) : 1;

		// 获得索引器
		IndexSearcher searcher = SystemToolkit.getIndexSearcher(Final.INDEX_GOODS);
		if (searcher == null)
		{
			return;
		}

		// 查询的结果放在这里集合
		List<Map<String, String>> qryGoodsList = new ArrayList<Map<String, String>>();

		// 查询条件
		Query q1 = new TermQuery(new Term("tags", keyword));
		Query q2 = new TermQuery(new Term("title", keyword));
		BooleanQuery query = new BooleanQuery();
		query.add(q1, BooleanClause.Occur.SHOULD);
		query.add(q2, BooleanClause.Occur.SHOULD);

		// 排序字段
		Sort sort = new Sort(new SortField[]
		{ new SortField("modifyTm", SortField.STRING, true) });
		TopDocs topDocs = searcher.search(query, null, pageSize * maxPageCount, sort);

		// 获得查询总记录数
		int numTotalHits = topDocs.totalHits;
		int totalPage = 0;
		if (numTotalHits > 0)
		{
			// 计算查询结果的总页数
			totalPage = (numTotalHits + pageSize - 1) / pageSize;
			// 规范查询页码
			page = page < 1 ? 1 : page > totalPage ? totalPage : page;
			// 查询起始记录位置
			int beginIdx = pageSize * (page - 1);
			// 查询终止记录位置
			int endIdx = Math.min(beginIdx + pageSize, numTotalHits);
			// 搜索返回的结果集合
			ScoreDoc[] hitDocs = topDocs.scoreDocs;

			Map<String, String> goodsMap = null;

			for (int i = beginIdx; i < endIdx; i++)
			{
				Document doc = searcher.doc(hitDocs[i].doc);

				goodsMap = new HashMap<String, String>();
				List<?> fls = doc.getFields();
				for (Object obj : fls)
				{
					Fieldable fieldable = (Fieldable) obj;
					String name = fieldable.name();
					String value = fieldable.stringValue();
					goodsMap.put(name, value);
				}
				qryGoodsList.add(goodsMap);
			}
		}
		searcher.close();

		// 设置值
		req.setAttribute("page", page);
		req.setAttribute("totalPage", totalPage);
		req.setAttribute("goodsList", qryGoodsList);
		req.getRequestDispatcher("/searchGoodsList.jsp").forward(req, resp);
	}
}
